package com.lagouedu.processor;

import com.lagouedu.pojo.Request;
import com.lagouedu.pojo.Response;
import com.lagouedu.servlet.HttpServlet;
import com.lagouedu.utils.HttpProtocolUtil;
import java.net.Socket;
import java.util.Map;

/**
 * @Author: chenhy
 * @Description:多线程请求处理
 * @Date: Create in 11:37 上午 2020/3/26
 */
public class RequestProcessor extends Thread {

  private Socket socket;

  private Map<String, Map<String, HttpServlet>> servletMap;

  public RequestProcessor(Socket socket, Map<String, Map<String, HttpServlet>> servletMap) {
    this.socket = socket;
    this.servletMap = servletMap;
  }

  @Override
  public void run() {
    try {
      Request request = new Request(socket.getInputStream());
      Response response = new Response(socket.getOutputStream());
      //相对url进行处理
      String[] split = request.getUrl().split("/");
      //第一个是项目名
      String projectName = split[1];
      Map<String, HttpServlet> httpServletMap = servletMap.get(projectName);
      if (null == httpServletMap || 0 == httpServletMap.size()) {
        //项目不存在，直接输出404
        response.output(HttpProtocolUtil.getHttpHeader404());
      } else {
        HttpServlet httpServlet = httpServletMap.get("/");
        httpServlet.service(request, response);
      }
      socket.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

